import { useState, useRef } from 'react'
import { Wrapper } from './FileBlob.styled'

export const Demo = () => {
  const ref = useRef<any>(null)
  const [fh, setFileHandle] = useState<any>(null)

  const onCreate = async () => {
    const filehandle = await (window as any).showSaveFilePicker();
    setFileHandle(filehandle)
    return filehandle;
  }
  const onOpen = async () => {
    const [filehandle] = await (window as any).showOpenFilePicker();
    setFileHandle(filehandle)
    const f = await filehandle.getFile()
    ref.current.value = await f.text()
  }
  const save = async (handle:any) => {
    if (!handle) return;
    const stream = await handle.createWritable();
    await stream.write(ref.current.value);
    await stream.close();
  }
  const onSaveAs = (isSave:boolean) => async (e:any) => {
    e.preventDefault();
    const filehandle = 
      (isSave && !!fh) ? fh : 
      await onCreate()
    ;
    save(filehandle)
  }

  return (
    <Wrapper>
      <textarea ref={ref} cols={36} rows={7}></textarea>
      <div>
        <button onClick={onCreate}>create</button>
        <button onClick={onOpen}>open</button>
        <button onClick={onSaveAs(true)}>save</button>
        <button onClick={onSaveAs(false)}>save as</button>
      </div>
    </Wrapper>
  )
}
